package com.heima.wemedia.filters;

import com.heima.wemedia.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class TokenFilter implements GlobalFilter, Ordered {

    // 检查token
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 登录放行
        if (request.getURI().toString().contains("/login")){
            return chain.filter(exchange);
        }
        // 获取token
        String token = request.getHeaders().getFirst("token");
        // 判断token是否有效
        if (token == null){
            return response.setComplete();
        }
        Claims claims = null;
        // 解析token
        try {
            claims = AppJwtUtil.getClaimsBody(token);
            // 检查token有效时间
            int time = AppJwtUtil.verifyToken(claims);
            if (time == 1 || time == 2){
                return response.setComplete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 有效, 设置请求头 userId
        String userId = claims.get("id").toString();
        ServerHttpRequest httpRequest = request.mutate().headers(httpHeaders ->
                httpHeaders.set("userId", userId)).build();
        // 重置请求
        exchange.mutate().request(httpRequest).build();
        // 放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
